'''
Created on 29.04.2013

@author: Thom
'''
import copy

from dame.Game import CheckersEvaluator

class Controller:
    
    _bestMove = None
    
    def getNextMove(self, board):
        self._bestMove = None
        
        maxDepth = 3
        evaluator = CheckersEvaluator()
        
        self.alphaBeta(board, evaluator, 0, maxDepth, evaluator.getMinValue(), evaluator.getMaxValue())
        
        return self._bestMove
        
    def alphaBeta(self, board, evaluator, depth, maxDepth, a, b):
    
        if (board.isTerminal()):
            return evaluator.exactValue(board)
        else:
            if (depth >= maxDepth):
                return evaluator.heuristicValue(board)
            else:
                while (board.hasNextMove()):
                    move = board.getNextMove()
                    
                    child = copy.deepcopy(board)
                    child.doMove(move)
                    
                    f = - self.alphaBeta(child, evaluator, depth+1, maxDepth, -b, -a)
                    if (f > a):
                        a = f
                        
                        if depth == 0:
                            self._bestMove = move
                        
                    if (a >= b):
                        return b #  cutoff
    
                return a